//
//  AppDelegate.swift
//  MQLWeibo
//
//  Created by MQL-IT on 2016/10/23.
//  Copyright © 2016年 MQL-IT. All rights reserved.
//

import UIKit
import UserNotifications
import SVProgressHUD
import AFNetworking


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        
        // 设置app额外设置
        window = UIWindow()
        window?.backgroundColor = UIColor.white
        window?.rootViewController = MainViewController()
        window?.makeKeyAndVisible()
        setUpAdditions()
        loadAppInfo()
        return true
    }
}

// MARK: - 设置app额外信息,, ****通用的东西
extension AppDelegate {
    fileprivate func setUpAdditions() {
        //1, 设置指示器的最小解除时间
        SVProgressHUD.setMinimumDismissTimeInterval(1)
        
        //2.设置网络加载指示器
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
        
        //3.设置用户授权显示通知
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge, .carPlay]) { (isSuccess, error) in
                
            }
        } else {
            // 取得用户授权显示通知(上方的提示条/声音/badgeNumber )
            let notifySettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(notifySettings)
        }
        
    }
    
}

//MARK: - 从服务器加载应用程序信息
extension AppDelegate {
    fileprivate func loadAppInfo() {
        //1.模拟异步
        DispatchQueue.global().async { 
            //1> url
            let url = Bundle.main.url(forResource: "main.json", withExtension: nil)
            //2> data
            let data = NSData(contentsOf: url!)
            //3> 写入磁盘
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
            //直接保存在沙盒中,等待下一次程序启动使用
            data?.write(toFile: jsonPath, atomically: true)
            print("网络应用程序加载完毕\(jsonPath)")
        }
    }
}
